use std::sync::Arc;

use deno_core::{op2, v8, OpState};
use thunderdome::Index;
use QcCore::{
    ecs::components::{
        material_render::{self, MaterialRender},
        mesh_render::MeshRender,
    },
    resources::{material::Material, ResourceManager},
};

use crate::utils::GoExt;

#[op2]
pub fn opSetMesh<'a>(
    state: &mut OpState,
    scope: &mut v8::HandleScope<'a>,
    this: v8::Local<v8::Object>,
    mesh: v8::Local<v8::Object>,
) -> v8::Local<'a, v8::Value> {
    let mut success = false;
    let mesh_render = GoExt::get_internal_field_mut::<MeshRender>(this, scope, 0);

    if let Some(mesh_render) = mesh_render {
        let key = v8::String::new(scope, "uuid").unwrap();

        let index = mesh.get(scope, key.into()).unwrap();
        let index = v8::Local::<v8::Number>::try_from(index).unwrap();
        let index = index.value() as u64;
        let index = Index::from_bits(index).unwrap();

        let resource_manager = state.borrow_mut::<Arc<ResourceManager>>();

        let mesh = resource_manager.get_mesh(index);
        
        if let Some(mesh) = mesh {
            mesh_render.set_mesh(0, mesh);
            success = true;
        } else {
            success = false;
        }
    } else {
        success = false;
    }

    v8::Boolean::new(scope, success).into()
}
